package com.qf.flash.ui.home;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.constraint.Group;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.qf.flash.R;
import com.qf.flash.event.FuckEvent;
import com.qf.flash.http.response.PlayConditinoResponse;
import com.qf.flash.http.response.PlayTypeBean;
import com.qf.flash.model.Pay2SponsorBean;
import com.qf.flash.model.ScriptRoomBean;
import com.qf.flash.mvp.contract.ScriptContract;
import com.qf.flash.mvp.presenter.ScriptPrensenter;
import com.qf.flash.ui.home.adapter.HotGridItem;
import com.qf.flash.ui.home.adapter.NumberItem;
import com.qf.flash.ui.home.adapter.ScriptRoomItem;
import com.qf.flash.ui.home.adapter.TypeItem;
import com.qf.flash.widget.GridSpaceItemDecoration;
import com.qf.flashlib.adapter.RVAdapter;
import com.qf.flashlib.app.FlashLib;
import com.qf.flashlib.base.BaseActivity;
import com.qf.flashlib.util.DateUtil;
import com.qf.flashlib.util.ViewUtil;

import org.greenrobot.eventbus.Subscribe;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.qf.flashlib.util.DateUtil.PATTERN_STANDARD16H;

/**
 * 2020/3/4 16:27
 * 剧本和密室
 */
public class ScriptRoomActivity extends BaseActivity implements ScriptContract.View {

    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.tv_top_right)
    TextView tvTopRight;
    @BindView(R.id.et_group_name)
    EditText etGroupName;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.rv_type)
    RecyclerView rvType;
    @BindView(R.id.rv_count)
    RecyclerView rvCount;
    @BindView(R.id.tv_hot_title)
    TextView tvHotTitle;
    @BindView(R.id.tv_hot_more)
    TextView tvHotMore;
    @BindView(R.id.group_hot)
    Group groupHot;
    @BindView(R.id.rv_hot)
    RecyclerView rvHot;
    @BindView(R.id.tv_sponsor)
    TextView tvSponsor;
    private boolean isRoom;

    private RVAdapter<PlayConditinoResponse.ThemesBean> mTypeAdapter;
    private RVAdapter<String> mNumberAdapter;
    private RVAdapter<ScriptRoomBean> mHotAdapter;

    private GridLayoutManager hotManager;
    private int spanCount = 3;
    private GridSpaceItemDecoration decoration = new GridSpaceItemDecoration(spanCount, (int) (FlashLib.density * 14));
    private ScriptPrensenter mScriptPresenter;


    private PlayTypeBean playTypeBean;  //模板
    private String isShop;      //是否是商家入口，1是，其他否

    private TimePickerView mTimePicker;
    private Date mSelectDate;


    //typeId	否	String	游戏类型id
    //name	否	String	剧本名称
    //theme	否	String	题材
    //num	否	Long	人数
    //isTop	否	String	是否是热门，0否，1是
    //money	否	Long	费用
    //pageNo	否	Integer	页数，默认从1开始
    //pageSize	否	Integer	每页多少条，默认30

    public static void start(Activity activity, PlayTypeBean playTypeBean, String isShop) {
        Intent intent = new Intent(activity, ScriptRoomActivity.class);
        intent.putExtra("playTypeBean", playTypeBean);
        intent.putExtra("isShop", isShop);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, PlayTypeBean playTypeBean) {
        start(activity, playTypeBean, "0");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_script_room;
    }

    @Override
    protected void initInject() {
        mScriptPresenter = new ScriptPrensenter();
        initPresenters(mScriptPresenter);
    }

    @Override
    protected void initViewAndData() {
        playTypeBean = getIntent().getParcelableExtra("playTypeBean");
        ViewUtil.setRightIcon(this, tvTopRight, R.mipmap.icon_search);
        isShop = getIntent().getStringExtra("isShop");
        isRoom = "2".equals(playTypeBean.getId());
        tvTopTitle.setText(isRoom ? "密室逃脱" : "剧本杀");
        tvHotTitle.setText(isRoom ? "热门主题" : "热门剧本");
        //初始化时间
        initTimeDialog();
        initRvType();
        initRvNumber();
        initRvHot();
        getPlayListHotData();
        mScriptPresenter.getConditions(playTypeBean.getTemplateId(), isShop);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.icon_search);
        if (drawable != null) {
            drawable.setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.icon_search);
        if (drawable != null) {
            drawable.setColorFilter(null);
        }
    }

    /**
     * 弹出选择时间
     */
    private void initTimeDialog() {
        //标题颜色
        int color = getResources().getColor(R.color.color_333333);
        //选中的时间
        Calendar selectedDate = Calendar.getInstance();
        if (mSelectDate != null)
            selectedDate.setTime(mSelectDate);
        //开始时间
        Calendar startDate = Calendar.getInstance();
        //结束时间
        Calendar endDate = Calendar.getInstance();
        endDate.set(2100, 11, 31);
        //构建选择器
        mTimePicker = new TimePickerBuilder(this, mTimeListener)
                .setType(new boolean[]{true, true, true, true, true, false})  // 默认全部显示
                .setOutSideCancelable(true)                                     //点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)                                                //是否循环滚动
                .setSubmitColor(color)                                          //确定按钮文字颜色
                .setCancelColor(color)                                          //取消按钮文字颜色
                .setDate(selectedDate)                                          // 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)
                .setLabel("年", "月", "日", "时", "分", "秒")                     //默认设置为年月日时分秒
                .isCenterLabel(false)                                            //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)                                                //是否显示为对话框样式
                .build();
    }

    /**
     * 选择时间监听
     */
    private OnTimeSelectListener mTimeListener = new OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            //记录时间
            mSelectDate = date;
            tvDate.setText(DateUtil.getDateToString(date.getTime(), PATTERN_STANDARD16H));
        }
    };

    private void getPlayListHotData() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("typeId", playTypeBean.getTemplateId());
        map.put("isTop", 1);
        map.put("pageNo", 1);
        map.put("pageSize", 6);
        mScriptPresenter.getPlayList(map);
    }

    private void getPlayListTypeData() {
        int typeChosenPosition = mTypeAdapter.getSingleChosenPosition();
        int numChosenPosition = mNumberAdapter.getSingleChosenPosition();

        HashMap<String, Object> map = new HashMap<>();
        map.put("typeId", playTypeBean.getTemplateId());
        map.put("isTop", 0);
        if (typeChosenPosition != -1 && typeChosenPosition != 0) {
            map.put("theme", mTypeAdapter.getData(typeChosenPosition).getId());
        }
        if (numChosenPosition != -1 && numChosenPosition != 0) {
            map.put("num", mNumberAdapter.getData(numChosenPosition));
        }

        map.put("pageNo", 1);
        map.put("pageSize", 6);
        mScriptPresenter.getPlayList(map);
    }


    private void initRvHot() {
        hotManager = new GridLayoutManager(this, spanCount);
        rvHot.setLayoutManager(hotManager);
        mHotAdapter = new RVAdapter<>(new HotGridItem(), new ScriptRoomItem(this));
        rvHot.setAdapter(mHotAdapter);
        mHotAdapter.setOnItemClickListener((view, position) -> {
            Pay2SponsorBean bean = getSponsorBean();
            bean.setPlayId(mHotAdapter.getData(position).getId());
            bean.setPlayName(mHotAdapter.getData(position).getName());
            ScriptDetailActivity.start(ScriptRoomActivity.this, bean, position);
        });
        mHotAdapter.setOnItemChildClickListener((view, position) -> {
            mHotAdapter.setSingleChosenPosition(position);
            mHotAdapter.notifyDataSetChanged();
        });
    }


    private void initRvType() {
        final LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvType.setLayoutManager(manager);
        mTypeAdapter = new RVAdapter<>(new TypeItem());
        rvType.setAdapter(mTypeAdapter);
        mTypeAdapter.setOnItemClickListener((view, position) -> {
            int singleChosenPosition = mTypeAdapter.getSingleChosenPosition();
            mTypeAdapter.setSingleChosenPosition(singleChosenPosition == position ? -1 : position);
            mTypeAdapter.notifyDataSetChanged();
            getPlayListTypeData();

        });

    }

    private void initRvNumber() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvCount.setLayoutManager(manager);
        mNumberAdapter = new RVAdapter<>(new NumberItem());
        mNumberAdapter.setOnItemClickListener((view, position) -> {
            int singleChosenPosition = mNumberAdapter.getSingleChosenPosition();
            mNumberAdapter.setSingleChosenPosition(singleChosenPosition == position ? -1 : position);
            mNumberAdapter.notifyDataSetChanged();
            getPlayListTypeData();
        });
        rvCount.setAdapter(mNumberAdapter);
    }


    private void sponsorGame() {
        if (TextUtils.isEmpty(etGroupName.getText())) {
            FlashLib.showToast("请输入组队名称");
            return;
        }
        if (TextUtils.isEmpty(tvDate.getText())) {
            FlashLib.showToast("请选择时间");
            return;
        }
        int chosenPosition = mHotAdapter.getSingleChosenPosition();
        if (chosenPosition == -1) {
            FlashLib.showToast("请选择剧本");
            return;
        }
        Pay2SponsorDialogFragment.newInstarnce(getSponsorBean())
                .show(getSupportFragmentManager());
    }

    private Pay2SponsorBean getSponsorBean() {
        Pay2SponsorBean bean = new Pay2SponsorBean();
        bean.setTeamName(etGroupName.getText().toString());
        bean.setStartTime(tvDate.getText().toString());
        int position = mNumberAdapter.getSingleChosenPosition();
        if (position != -1 && position != 0) {
            String data = mNumberAdapter.getData(position);
            bean.setNum(data);
        }
        bean.setPlayType(playTypeBean.getTemplateId());
        int typePos = mTypeAdapter.getSingleChosenPosition();
        if (typePos != -1 && typePos != 0) {
            bean.setPlayTypeName(mTypeAdapter.getData(typePos).getName());
        }

        bean.setPassword(etPassword.getText().toString());
        int chosenPosition = mHotAdapter.getSingleChosenPosition();
        if (chosenPosition != -1) {
            bean.setPlayId(mHotAdapter.getData(chosenPosition).getId());
            bean.setPlayName(mHotAdapter.getData(chosenPosition).getName());
            bean.setMoney(mHotAdapter.getData(chosenPosition).getDownpayment());
        }
        return bean;
    }


    @OnClick({R.id.tv_top_back, R.id.tv_date, R.id.tv_hot_more, R.id.tv_sponsor, R.id.ll_top_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_top_back:
                finish();
                break;
            case R.id.tv_date:
                if (mTimePicker != null)
                    hideInput();
                mTimePicker.show();
                break;
            case R.id.tv_hot_more:
                Pay2SponsorBean bean = getSponsorBean();
                HotActivity.start(this, bean, playTypeBean.getTemplateId(), false);
                break;
            case R.id.ll_top_right:
                Pay2SponsorBean pay2SponsorBean = getSponsorBean();
                String hint = isRoom ? "请输入密室名称" : "请输入剧本名称";
                ScriptSearchActivity.start(this, pay2SponsorBean, hint);
                break;
            case R.id.tv_sponsor:
                if (mHotAdapter.getSingleChosenPosition() != -1)
                    sponsorGame();
                else
                    FlashLib.showToast("请选择剧本");
                break;
        }
    }

    @Override
    public void setPlayListData(List<ScriptRoomBean> data, int totalPage) {
        int mNumberPos= mNumberAdapter.getSingleChosenPosition();
        int typePos = mTypeAdapter.getSingleChosenPosition();
        if ((mNumberPos != -1 && mNumberPos != 0) || (typePos != -1 && typePos != 0)) {
            for (ScriptRoomBean datum : data) {
                datum.setSpanSize(3);
            }
            groupHot.setVisibility(View.GONE);
            rvHot.removeItemDecoration(decoration);
        } else {
            groupHot.setVisibility(View.VISIBLE);
            if (rvHot.getItemDecorationCount() == 0)
                rvHot.addItemDecoration(decoration);
        }
        mHotAdapter.setSingleChosenPosition(-1);
        mHotAdapter.setDatas(data);
    }

    @Override
    public void setConditionData(PlayConditinoResponse response) {
        List<PlayConditinoResponse.ThemesBean> themes = response.getThemes();
        PlayConditinoResponse.ThemesBean bean = new PlayConditinoResponse.ThemesBean();
        bean.setName("全部");
        themes.add(0, bean);
        mTypeAdapter.setSingleChosenPosition(0);
        mTypeAdapter.setDatas(themes);
        List<String> nums = response.getNums();
        nums.add(0, "全部");
        mNumberAdapter.setSingleChosenPosition(0);
        mNumberAdapter.setDatas(nums);
    }

    @Override
    protected boolean useEvent() {
        return true;
    }

    @Subscribe
    public void onFuckEvent(FuckEvent event) {
        if (event.getPosition() != -1) {
            mHotAdapter.setSingleChosenPosition(event.getPosition());
            mHotAdapter.notifyDataSetChanged();
        }
    }


    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
}
